<template>
  <div class="app-container">
    <el-container>
      <el-aside width="200px">
        <el-menu
          :router="true"
          class="el-menu-vertical"
          default-active="/"
        >
          <el-menu-item index="/">
            <el-icon><el-icon-house /></el-icon>
            <span>首页</span>
          </el-menu-item>
          <el-menu-item index="/forwarding">
            <el-icon><el-icon-message /></el-icon>
            <span>消息转发</span>
          </el-menu-item>
          <el-menu-item index="/settings">
            <el-icon><el-icon-setting /></el-icon>
            <span>设置</span>
          </el-menu-item>
          <el-menu-item index="/logs">
            <el-icon><el-icon-document /></el-icon>
            <span>日志</span>
          </el-menu-item>
        </el-menu>
        <div class="service-status">
          <div class="status-indicator" :class="{ 'active': wechatStore.isRunning }"></div>
          <span>服务状态: {{ wechatStore.isRunning ? '运行中' : '已停止' }}</span>
          <div v-if="wechatStore.isRunning" class="login-status">
            <div class="status-indicator" :class="{ 'active': isLoggedIn }"></div>
            <span>登录状态: {{ isLoggedIn ? '已登录' : '未登录' }}</span>
          </div>
        </div>
      </el-aside>
      <el-container>
        <el-header>
          <div class="header-title">微信消息转发助手</div>
          <div class="header-actions">
            <el-button 
              type="primary" 
              size="small" 
              @click="toggleWechatService"
              :loading="isLoading"
            >
              {{ wechatStore.isRunning ? '停止服务' : '启动服务' }}
            </el-button>
            
            <el-button
              v-if="wechatProcess && !isLoggedIn"
              type="success"
              size="small"
              @click="checkLoginStatus"
              :loading="isCheckingLogin"
            >
              我已登录
            </el-button>
          </div>
        </el-header>
        <el-main>
          <el-card v-if="!isLoggedIn" class="guide-card">
            <template #header>
              <div class="card-header">
                <span>操作指南</span>
              </div>
            </template>
            <el-steps :active="activeStep" finish-status="success">
              <el-step title="启动服务" description="点击右上角'启动服务'按钮"></el-step>
              <el-step title="登录微信" description="使用微信扫码完成授权"></el-step>
              <el-step title="确认登录" description="授权完成后点击'我已登录'按钮"></el-step>
              <el-step title="配置转发" description="在转发菜单中配置转发规则"></el-step>
            </el-steps>
          </el-card>
          
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useWechatStore } from './store';
import { ElMessage } from 'element-plus';
import { 
  House as ElIconHouse,
  Message as ElIconMessage,
  Setting as ElIconSetting,
  Document as ElIconDocument
} from '@element-plus/icons-vue';

// 状态管理
const wechatStore = useWechatStore();
const isLoading = ref(false);
const isCheckingLogin = ref(false);
// 使用计算属性从 Pinia store 获取登录状态
const isLoggedIn = computed(() => wechatStore.isLoggedIn);
const wechatProcess = ref(false);

// 指南步骤状态
const activeStep = computed(() => {
  if (!wechatProcess.value) return 0;  // 第一步：启动服务
  if (wechatProcess.value && !isLoggedIn.value) return 1; // 第二步：登录微信
  if (isLoggedIn.value) return 3; // 第四步：配置转发
  return 0;
});

// 启动/停止微信服务
async function toggleWechatService() {
  isLoading.value = true;
  try {
    console.log('正在操作微信服务，当前状态:', wechatStore.isRunning ? '运行中' : '已停止');
    
    if (wechatStore.isRunning) {
      console.log('尝试停止服务...');
      await window.electronAPI.stopWechatService();
      ElMessage.success('微信服务已停止');
      
      // 重置状态
      wechatProcess.value = false;
      wechatStore.clearUserInfo(); // 清除用户信息和登录状态
      wechatStore.updateStatus({ running: false, loggedIn: false });
    } else {
      console.log('尝试启动服务...');
      ElMessage.info('正在启动微信服务，这可能需要一些时间...');
      const result = await window.electronAPI.startWechatService();
      console.log('服务启动结果:', result);
      
      if (result) {
        wechatProcess.value = true;
        wechatStore.updateStatus({ running: true, loggedIn: false });
        ElMessage.success('微信服务已启动');
        ElMessage.info('请在微信上完成登录授权后，点击"我已登录"按钮');
      } else {
        ElMessage.error('微信服务启动失败，请查看控制台获取更多信息');
      }
    }
  } catch (error) {
    console.error('操作服务时出错:', error);
    ElMessage.error(`操作失败: ${error.message}`);
  } finally {
    isLoading.value = false;
  }
}

// 检查微信服务状态
async function checkWechatService() {
  try {
    const status = await window.electronAPI.checkWechatService();
    wechatStore.updateStatus(status);
    
    // 更新登录状态
    if (status.loggedIn !== undefined) {
      isLoggedIn.value = status.loggedIn;
    }
    
    // 如果服务不运行，重置登录状态
    if (!status.running) {
      isLoggedIn.value = false;
      wechatProcess.value = false;
    }
    return status;
  } catch (error) {
    console.error('检查服务状态失败:', error);
    return { running: false, error: error.message };
  }
}

// 添加检查登录状态的函数
async function checkLoginStatus() {
  isCheckingLogin.value = true;
  try {
    console.log('检查微信登录状态...');
    const loginResult = await window.electronAPI.getWechatApi('/wcf/is_login');
    console.log('登录状态检查结果:', loginResult);
    
    // 检查返回的数据格式
    if (loginResult && loginResult.Payload === true) {
      // 更新 Pinia store
      wechatStore.updateStatus({ running: true, loggedIn: true });
      
      // 额外获取用户信息
      try {
        const userInfo = await window.electronAPI.postWechatApi('/wcf/self_info', {
          is_chatroom: false
        });
        console.log('获取用户信息成功:', userInfo);
        if (userInfo && userInfo.Payload) {
          wechatStore.setUserInfo(userInfo.Payload);
        }
      } catch (infoError) {
        console.error('获取用户信息失败:', infoError);
      }
      
      ElMessage.success('微信已登录，服务已激活');
      ElMessage.success('现在您可以在"消息转发"页面配置转发规则');
    } else {
      wechatStore.updateStatus({ running: true, loggedIn: false });
      ElMessage.warning('微信未登录，请确认已在微信上完成授权后再点击"我已登录"按钮');
    }
  } catch (error) {
    console.error('检查登录状态时出错:', error);
    ElMessage.error(`检查失败: ${error.message}`);
    wechatStore.updateStatus({ running: true, loggedIn: false });
  } finally {
    isCheckingLogin.value = false;
  }
}

// 组件挂载时
onMounted(() => {
  // 检查微信服务状态
  checkWechatService().then(status => {
    // 如果检测到服务已在运行，更新 wechatProcess 状态
    if (status && status.running) {
      console.log('检测到微信服务已在运行');
      wechatProcess.value = true;
      
      // 同时检查登录状态
      if (status.loggedIn) {
        console.log('检测到微信已登录');
        // 不需要设置 isLoggedIn，它会通过计算属性从 store 获取
        wechatStore.updateStatus({ running: true, loggedIn: true });
        ElMessage.success('微信已登录，服务已激活');
      } else {
        ElMessage.info('微信服务已启动，请在微信上完成登录授权后，点击"我已登录"按钮');
      }
    }
  });
  
  // 设置事件监听
  window.electronAPI.onWechatLog((log) => {
    wechatStore.addLog(log);
  });
  
  window.electronAPI.onWechatError((error) => {
    wechatStore.addError(error);
  });
  
  window.electronAPI.onWechatStatus((status) => {
    wechatStore.updateStatus(status);
    
    // 如果服务是运行状态，更新 wechatProcess
    if (status.running && !wechatProcess.value) {
      wechatProcess.value = true;
    }
    
    // 如果服务停止，重置登录状态
    if (!status.running) {
      wechatProcess.value = false;
      wechatStore.clearUserInfo(); // 确保清除用户信息
    }
  });
  
  // 定期检查服务状态
  const statusInterval = setInterval(checkWechatService, 10000);
  
  // 清理定时器
  onUnmounted(() => {
    clearInterval(statusInterval);
    window.electronAPI.removeAllListeners();
  });
});
</script>

<style>
.app-container {
  height: 100vh;
  width: 100vw;
}

.el-header {
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  border-bottom: 1px solid #e6e6e6;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.el-aside {
  background-color: #304156;
  color: #fff;
}

.el-menu-vertical {
  height: calc(100vh - 60px);
  border-right: none;
}

.service-status {
  position: absolute;
  bottom: 20px;
  left: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: #fff;
  font-size: 14px;
}

.status-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #f56c6c;
  margin-right: 8px;
  display: inline-block;
}

.status-indicator.active {
  background-color: #67c23a;
}

.login-status {
  margin-top: 5px;
  padding-top: 5px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.login-status > span {
  display: flex;
  align-items: center;
}

.el-main {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100vh - 60px);
  overflow-y: auto;
}

.guide-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 